using System.IO;

namespace SB2.Core
{
    /// <summary>
    /// 附件
    /// </summary>
    public class FileAppService : ICoreService
    {
        public FileAppService()
        {
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        [RequestSizeLimit(100_000_000)]
        public async Task<List<string>> Add(List<IFormFile> files)
        {
            if (files != null && files.Any())
            {
                var res = new List<string>();
                // 保存到网站根目录下的 uploads 目录
                var savePath = Path.Combine(App.HostEnvironment.ContentRootPath, "uploads");
                if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
                // 总上传大小
                long size = files.Sum(f => f.Length);
                // 遍历所有文件逐一上传
                foreach (var formFile in files)
                {
                    if (formFile.Length > 0)
                    {
                        // 避免文件名重复，采用 GUID 生成
                        var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(formFile.FileName);
                        var filePath = Path.Combine(savePath, fileName);
                        // 保存到指定路径
                        using (var stream = System.IO.File.Create(filePath))
                        {
                            await formFile.CopyToAsync(stream);
                        }
                        res.Add(fileName);
                    }
                }
                return res;
            }
            throw Oops.Oh("没有文件！"); ;
        }



        /// <summary>
        /// base64 上传
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [RequestSizeLimit(100_000_000)]
        public async Task<List<string>> Base64(List<FileInfoRequest> files)
        {
            if (files != null && files.Any())
            {
                var res = new List<string>();
                // 保存到网站根目录下的 uploads 目录
                var savePath = Path.Combine(App.HostEnvironment.ContentRootPath, "uploads");
                if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
                // 遍历所有文件逐一上传
                foreach (var formFile in files)
                {
                    try
                    {
                        // 避免文件名重复，采用 GUID 生成
                        var fileName = Guid.NewGuid().ToString("N") + Path.GetExtension(formFile.FileName);
                        var filePath = Path.Combine(savePath, fileName);
                        var bytes = Convert.FromBase64String(formFile.FileBase64.Replace("data:image/png;base64,", ""));
                        // 保存到指定路径
                        using (var fs = new FileStream(filePath, FileMode.Create))
                        {
                            await fs.WriteAsync(bytes);
                        }
                        res.Add(fileName);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"保存base64文件出错！{e.Message}");
                    }
                }
                return res;
            }
            throw Oops.Oh("没有文件！"); ;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        [RequestSizeLimit(100_000_000)]
        public async Task<List<string>> put(List<IFormFile> files)
        {
            if (files != null && files.Any())
            {
                var res = new List<string>();
                // 保存到网站根目录下的 uploads 目录
                var savePath = Path.Combine(App.HostEnvironment.ContentRootPath, "uploads");
                if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
                // 总上传大小
                long size = files.Sum(f => f.Length);
                // 遍历所有文件逐一上传
                foreach (var formFile in files)
                {
                    if (formFile.Length > 0)
                    {
                        // 避免文件名重复，采用 GUID 生成
                        var filePath = Path.Combine(savePath, formFile.FileName);
                        // 保存到指定路径
                        using (var stream = System.IO.File.Create(filePath))
                        {
                            await formFile.CopyToAsync(stream);
                        }
                        res.Add(formFile.FileName);
                    }
                }
                return res;
            }
            throw Oops.Oh("没有文件！"); ;
        }
        [RequestSizeLimit(100_000_000)]
        [HttpPut]
        public async Task<List<string>> PutBase64(List<FileInfoRequest> files)
        {
            if (files != null && files.Any())
            {
                var res = new List<string>();
                // 保存到网站根目录下的 uploads 目录
                var savePath = Path.Combine(App.HostEnvironment.ContentRootPath, "uploads");
                if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);
                // 遍历所有文件逐一上传
                foreach (var formFile in files)
                {
                    try
                    {
                        // 避免文件名重复，采用 GUID 生成
                        var fileName = formFile.FileName;
                        var filePath = Path.Combine(savePath, fileName);
                        var bytes = Convert.FromBase64String(formFile.FileBase64.Replace("data:image/png;base64,", ""));
                        // 保存到指定路径
                        using (var fs = new FileStream(filePath, FileMode.Create))
                        {
                            await fs.WriteAsync(bytes);
                        }
                        res.Add(fileName);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"保存base64文件出错！{e.Message}");
                        throw Oops.Oh("保存文件出错"); ;
                    }
                }
                return res;
            }
            throw Oops.Oh("没有文件！"); ;
        }
    }
}